# OAuth认证服务
import requests
from flask import current_app, session, redirect, url_for, request, flash
from flask_login import login_user
from app.models.user import User
from app.extensions import db

class OAuthService:
    """OAuth认证服务类"""
    
    @staticmethod
    def get_github_authorize_url():
        """获取GitHub授权URL"""
        client_id = current_app.config.get('GITHUB_CLIENT_ID')
        redirect_uri = current_app.config.get('OAUTH_REDIRECT_URI')
        scope = 'user:email'
        
        return (f'https://github.com/login/oauth/authorize?'
                f'client_id={client_id}&'
                f'redirect_uri={redirect_uri}&'
                f'scope={scope}')
    
    @staticmethod
    def get_github_access_token(code):
        """获取GitHub访问令牌"""
        client_id = current_app.config.get('GITHUB_CLIENT_ID')
        client_secret = current_app.config.get('GITHUB_CLIENT_SECRET')
        redirect_uri = current_app.config.get('OAUTH_REDIRECT_URI')
        
        token_url = 'https://github.com/login/oauth/access_token'
        data = {
            'client_id': client_id,
            'client_secret': client_secret,
            'code': code,
            'redirect_uri': redirect_uri
        }
        
        headers = {'Accept': 'application/json'}
        response = requests.post(token_url, data=data, headers=headers)
        
        if response.status_code == 200:
            token_data = response.json()
            return token_data.get('access_token')
        
        return None
    
    @staticmethod
    def get_github_user_info(access_token):
        """获取GitHub用户信息"""
        user_url = 'https://api.github.com/user'
        headers = {
            'Authorization': f'token {access_token}',
            'Accept': 'application/json'
        }
        
        response = requests.get(user_url, headers=headers)
        
        if response.status_code == 200:
            return response.json()
        
        return None
    
    @staticmethod
    def get_github_user_emails(access_token):
        """获取GitHub用户邮箱"""
        emails_url = 'https://api.github.com/user/emails'
        headers = {
            'Authorization': f'token {access_token}',
            'Accept': 'application/json'
        }
        
        response = requests.get(emails_url, headers=headers)
        
        if response.status_code == 200:
            emails = response.json()
            # 返回主邮箱（已验证且公开的邮箱）
            primary_emails = [email['email'] for email in emails if email['primary'] and email['verified']]
            if primary_emails:
                return primary_emails[0]
            # 如果没有主邮箱，返回第一个已验证的邮箱
            verified_emails = [email['email'] for email in emails if email['verified']]
            if verified_emails:
                return verified_emails[0]
        
        return None
    
    @staticmethod
    def authenticate_with_github(code):
        """使用GitHub进行OAuth认证"""
        # 获取访问令牌
        access_token = OAuthService.get_github_access_token(code)
        if not access_token:
            return None, "无法获取访问令牌"
        
        # 获取用户信息
        user_info = OAuthService.get_github_user_info(access_token)
        if not user_info:
            return None, "无法获取用户信息"
        
        # 获取用户邮箱
        email = OAuthService.get_github_user_emails(access_token)
        if not email:
            email = f"{user_info['login']}@github.local"  # 使用GitHub用户名创建临时邮箱
        
        # 查找或创建用户
        user = User.query.filter_by(email=email).first()
        
        if not user:
            # 创建新用户
            username = user_info['login']
            # 确保用户名唯一
            base_username = username
            counter = 1
            while User.query.filter_by(username=username).first():
                username = f"{base_username}{counter}"
                counter += 1
            
            user = User(
                username=username,
                email=email,
                nickname=user_info.get('name') or user_info['login'],
                bio=user_info.get('bio'),
                avatar=user_info.get('avatar_url'),
                website=user_info.get('blog'),
                is_active=True,
                is_public=True
            )
            
            # 设置随机密码（OAuth用户不使用密码登录）
            import secrets
            random_password = secrets.token_urlsafe(16)
            user.set_password(random_password)
            
            db.session.add(user)
            db.session.commit()
            
            # 为新用户分配默认角色
            from app.models.init_roles import init_roles_and_permissions
            init_roles_and_permissions()
            
            from app.models.role import Role
            viewer_role = Role.query.filter_by(name='viewer').first()
            if viewer_role:
                user.add_role(viewer_role)
                db.session.commit()
        
        # 更新用户信息
        if user_info.get('name'):
            user.nickname = user_info['name']
        if user_info.get('bio'):
            user.bio = user_info['bio']
        if user_info.get('avatar_url'):
            user.avatar = user_info['avatar_url']
        if user_info.get('blog'):
            user.website = user_info['blog']
        
        db.session.commit()
        
        return user, None